package com.fubowen.reader.ui.download

import android.content.pm.PackageManager
import android.os.Bundle
import android.os.Environment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.lifecycle.lifecycleScope
import com.fubowen.reader.R
import com.fubowen.reader.databinding.FragmentScanExplorerBinding
import com.fubowen.reader.extension.searchFilePFS
import com.fubowen.reader.db.model.PermissionState
import com.fubowen.reader.db.model.Tree
import com.fubowen.reader.db.model.toTreeItem
import com.fubowen.reader.ui.fragment.MANAGE_EXTERNAL_STORAGE
import com.fubowen.reader.ui.fragment.TreeFragment
import kotlinx.coroutines.launch
import java.io.File

class ScanExplorerFragment : TreeFragment() {

    private lateinit var binding: FragmentScanExplorerBinding

    override val isEnableBreadcrumb = false

    //region onItemClick，onSelectedClick，onCreateView

    override fun onItemClick(view: View, item: Tree, position: Int) {
        item.isChecked = !item.isChecked
        if (item.isChecked) cacheViewModel.select(item) else cacheViewModel.delete(item)
        adapter.notifyItemChanged(position)
    }

    override fun onItemButtonClick(view: View, item: Tree, position: Int) {}

    override fun onSizeChanged(size: Int) {
        binding.selected.text = getString(R.string.checkedText, size)
    }

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View {
        super.onCreateView(inflater, container, savedInstanceState)
        binding = FragmentScanExplorerBinding.inflate(inflater)
        super.initRecyclerView(binding.root)
        pagePermission[MANAGE_EXTERNAL_STORAGE] = getString(R.string.scan_explorer_permission)
        binding.selected.setOnClickListener { openSelected() }
        observerUpdate()
        return binding.root
    }

    //endregion

    //region showIncludeFileListInRecyclerView，observerUpdate，openSelected
    private fun showIncludeFileListInRecyclerView(book: Tree) {
        showLoading("正在扫描本地书籍...")
        lifecycleScope.launch {
            val items = searchFilePFS(File(book.absolutePath))
            adapter.submitList(items)
            hideLoading()
        }
    }

    private fun observerUpdate() {
        lifecycleScope.launch {
            cacheViewModel.updateFlow.collect { item ->
                val index = adapter.currentList.indexOfFirst { it.absolutePath == item.absolutePath }
                if (index != -1) {
                    adapter.notifyItemChanged(index, item)
                }
            }
        }
    }

    private fun openSelected() = selector.value.show(parentFragmentManager, SELECTED_DIALOG_TAG)
    //endregion

    //region onChangedPermission
    override fun onChangedPermission(state: PermissionState) {
        super.onChangedPermission(state)
        if (state.permission == MANAGE_EXTERNAL_STORAGE) {
            when (state.state) {
                PackageManager.PERMISSION_GRANTED -> {
                    val book = Environment.getExternalStorageDirectory().toTreeItem()
                    book.name = "内部存储"
                    showIncludeFileListInRecyclerView(book)
                }
            }
        }
    }
    //endregion
}
